<template>
  <el-dialog
    v-model="visible"
    title="添加外部URL"
    width="800"
    draggable
    @close="close"
    :z-index="2000"
  >
    <el-input
      v-model="textarea"
      :autosize="{ minRows: 10, maxRows: 50 }"
      type="textarea"
      placeholder="请输入图片URL，多个URL请回车换行"
    />
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ExternalUrl">
import { nextTick, toRaw } from "vue";
import { ElMessage } from "element-plus";
import { uploadImg } from "@/api/index.js";

const props = defineProps({
  customTag: {
    type: String,
    default: () => "",
  },
});
const textarea = ref("");
const emits = defineEmits(["uploadFile"]);
const source = ref(1);
const imageType = ref(0);
const loading = ref(false);
const visible = ref(null);
const uploadList = ref([]);
const open = (type) => {
  visible.value = true;
  imageType.value = type;
  uploadList.value = [];
};
// 图片名称尺寸
const imgInfo = (url) => {
  let obj = {};
  let image = new Image();
  image.src = url;
  image.onload = () => {
    obj.image_name = urlName(url);
    obj.image_type = imageType.value;
    obj.custom_tag = props.customTag;
    obj.image_source = 5;
    obj.image_for = "";
    obj.image_link = url;
    obj.image_size = `${image.width} * ${image.width}`;
    obj.usage_status = 1;
  };
  return obj;
};
// url图片名称
const urlName = (url) => {
  let filename = "";
  if (url.indexOf("/") > 0) {
    if (url.indexOf("?") > 0) {
      url = url.split("?")[0];
    }
    //如果包含有"/"号 从最后一个"/"号+1的位置开始截取字符串
    filename = url.substring(url.lastIndexOf("/") + 1, url.length);
  }
  return filename;
};

const close = () => {
  visible.value = false;
};
const save = async () => {
  if (!textarea.value) return ElMessage.error("请输入图片链接");
  let str =
    textarea.value && textarea.value.replace(/ /g, "&nbsp;").replace(/\n|\r\n/g, "/n");
  let strArr = str.split("/n");
  // strArr.forEach((item) => {
  //   uploadList.value.push(imgInfo(item));
  // });

  for (let item of strArr) {
    try {
      const blob = await downloadImage(item);
      const ossUrl = await uploadToOSS(blob);
      uploadList.value.push(imgInfo(ossUrl));
    } catch (error) {
      ElMessage.error(`上传图片失败: ${error.message}`);
    }
  }
  console.log(uploadList.value);

  setTimeout(() => {
    textarea.value = "";
    if (!uploadList.value.length) return ElMessage.error(`请输入图片链接`);
    emits("uploadFile", uploadList.value, imageType.value);
    close();
  }, 300);
};

defineExpose({ open });

const downloadImage = async (url) => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to download image: ${response.statusText}`);
  }
  return await response.blob();
};

const uploadToOSS = async (blob) => {
  let formData = new FormData();
  formData.append("file", blob);
  try {
    const { data } = await uploadImg(formData);
    return data["data-show-file"];
  } catch (error) {
    consol.error(error);
  }
};
</script>
<style lang="scss" scoped></style>
